#include <iostream>
#include <stack>
#include <vector>
struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 };
using namespace std;


class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> v;
        stack<TreeNode*> st;

        //先入根
        TreeNode* cur = root;
        while(cur||!st.empty())
        {
            //先入cur的所有左节点
            //在访问cur的左路节点
            while(cur)
            {
                st.push(cur);
                v.push_back(cur->val);
                cur = cur->left;
            }
            TreeNode* top = st.top();
            st.pop();
            if(top)
                top = top->right;
            cur = top;
        }
        return v;
    }
};